package src;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class UsageInfoPanel extends JDialog {
    private Connection connection;
    private JTable usageTable;
    private JTextField idField, usageDateField, amountField;
    private JComboBox<String> customerIdField;
    private JButton addButton, updateButton, deleteButton, searchButton;
    private JPanel inputPanel;
    private JComboBox<String> waterTypeCombo;

    public UsageInfoPanel(Connection connection) {
        super((JFrame) null, "客户用水信息管理", true);
        this.connection = connection;
        setSize(1000, 700);
        setLocationRelativeTo(null);
        getContentPane().setBackground(StyleConstants.BACKGROUND_COLOR);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(StyleConstants.THEME_COLOR);
        JLabel titleLabel = new JLabel("客户用水信息管理", JLabel.CENTER);
        titleLabel.setFont(StyleConstants.TITLE_FONT);
        titleLabel.setForeground(Color.WHITE);
        titlePanel.add(titleLabel);
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"ID", "客户", "抄表日期", "读数", "用水类型"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        usageTable = new JTable(tableModel);
        usageTable.setFont(StyleConstants.TABLE_FONT);
        usageTable.getTableHeader().setFont(StyleConstants.TABLE_FONT);
        usageTable.setRowHeight(25);
        usageTable.setGridColor(StyleConstants.THEME_COLOR);
        JScrollPane scrollPane = new JScrollPane(usageTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建输入面板
        inputPanel = new JPanel(new GridLayout(6, 2, 10, 10));
        inputPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        addInputField(inputPanel, "ID:", idField = new JTextField());
        
        // 添加客户下拉框
        customerIdField = new JComboBox<>();
        customerIdField.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_id, name FROM customer");
            while (rs.next()) {
                String customerId = rs.getString("customer_id");
                String customerName = rs.getString("name");
                customerIdField.addItem(customerName + " (" + customerId + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载客户信息失败: " + e.getMessage());
        }
        addComboBox("客户:", customerIdField);
        
        addInputField(inputPanel, "抄表日期:", usageDateField = new JTextField());
        addInputField(inputPanel, "读数:", amountField = new JTextField());
        
        // 添加用水类型下拉框
        waterTypeCombo = new JComboBox<>();
        waterTypeCombo.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT type_name FROM water_type");
            while (rs.next()) {
                waterTypeCombo.addItem(rs.getString("type_name"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载用水类型失败: " + e.getMessage());
        }
        addComboBox("用水类型:", waterTypeCombo);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(StyleConstants.BACKGROUND_COLOR);

        addButton = createStyledButton("添加");
        updateButton = createStyledButton("更新");
        deleteButton = createStyledButton("删除");
        searchButton = createStyledButton("查找");

        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(searchButton);

        // 将输入面板和按钮面板添加到主面板
        JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
        bottomPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        bottomPanel.add(inputPanel, BorderLayout.CENTER);
        bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        add(mainPanel);
        refreshTable();

        // 添加表格选择监听器
        usageTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = usageTable.getSelectedRow();
                if (selectedRow != -1) {
                    idField.setText(usageTable.getValueAt(selectedRow, 0).toString());
                    
                    // 设置客户下拉框选中项
                    String selectedCustomer = usageTable.getValueAt(selectedRow, 1).toString();
                    for (int i = 0; i < customerIdField.getItemCount(); i++) {
                        String item = customerIdField.getItemAt(i);
                        if (item != null && item.equals(selectedCustomer)) {
                            customerIdField.setSelectedIndex(i);
                            break;
                        }
                    }
                    
                    usageDateField.setText(usageTable.getValueAt(selectedRow, 2).toString());
                    amountField.setText(usageTable.getValueAt(selectedRow, 3).toString());
                    
                    // 设置用水类型下拉框选中项
                    String selectedWaterType = usageTable.getValueAt(selectedRow, 4).toString();
                    for (int i = 0; i < waterTypeCombo.getItemCount(); i++) {
                        String item = waterTypeCombo.getItemAt(i);
                        if (item != null && item.equals(selectedWaterType)) {
                            waterTypeCombo.setSelectedIndex(i);
                            break;
                        }
                    }
                }
            }
        });

        // 添加按钮事件监听器
        addButton.addActionListener(e -> {
            UsageAddDialog dialog = new UsageAddDialog(this, connection);
            dialog.setVisible(true);
            refreshTable();
        });
        updateButton.addActionListener(e -> updateUsage());
        deleteButton.addActionListener(e -> deleteUsage());
        searchButton.addActionListener(e -> searchUsage());
    }

    private void addInputField(JPanel panel, String labelText, JTextField textField) {
        JLabel label = new JLabel(labelText);
        label.setFont(StyleConstants.LABEL_FONT);
        panel.add(label);
        textField.setFont(StyleConstants.LABEL_FONT);
        panel.add(textField);
    }

    private void addComboBox(String labelText, JComboBox<String> comboBox) {
        JLabel label = new JLabel(labelText);
        label.setFont(StyleConstants.LABEL_FONT);
        inputPanel.add(label);
        comboBox.setFont(StyleConstants.LABEL_FONT);
        inputPanel.add(comboBox);
    }

    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setFont(StyleConstants.BUTTON_FONT);
        button.setBackground(StyleConstants.BUTTON_COLOR);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(StyleConstants.BUTTON_COLOR.darker());
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(StyleConstants.BUTTON_COLOR);
            }
        });

        return button;
    }

    private void refreshTable() {
        DefaultTableModel model = (DefaultTableModel) usageTable.getModel();
        model.setRowCount(0);
        
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery(
                 "SELECT b.bill_id, b.customer_id, c.name as customer_name, b.reading_date, b.current_reading, w.type_name " +
                 "FROM water_bill b " +
                 "LEFT JOIN customer c ON b.customer_id = c.customer_id " +
                 "LEFT JOIN water_type w ON b.water_type_id = w.water_type_id")) {
            while (rs.next()) {
                String customerName = rs.getString("customer_name");
                String customerId = rs.getString("customer_id");
                String customerDisplay = customerName != null ? 
                    customerName + " (" + customerId + ")" : customerId;
                
                model.addRow(new Object[]{
                    rs.getString("bill_id"),
                    customerDisplay,
                    rs.getString("reading_date"),
                    rs.getDouble("current_reading"),
                    rs.getString("type_name")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载用水信息数据失败: " + e.getMessage());
        }
    }

    private void updateUsage() {
        try {
            // 获取用水类型ID
            String waterTypeId = getWaterTypeId(waterTypeCombo.getSelectedItem().toString());
            if (waterTypeId == null) {
                JOptionPane.showMessageDialog(this, "无效的用水类型！");
                return;
            }

            // 从客户选择框中提取客户ID
            String selectedCustomer = customerIdField.getSelectedItem().toString();
            String customerId = selectedCustomer.substring(selectedCustomer.lastIndexOf("(") + 1, selectedCustomer.lastIndexOf(")"));

            String sql = "UPDATE water_bill SET customer_id=?, reading_date=?, current_reading=?, water_type_id=? WHERE bill_id=?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, customerId);
            pstmt.setString(2, usageDateField.getText());
            pstmt.setDouble(3, Double.parseDouble(amountField.getText()));
            pstmt.setString(4, waterTypeId);
            pstmt.setString(5, idField.getText());
            
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "用水信息更新成功！");
            clearFields();
            refreshTable();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "更新用水信息失败: " + e.getMessage());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "读数必须是数字！");
        } catch (StringIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "客户信息格式不正确！");
        }
    }

    private String getWaterTypeId(String typeName) throws SQLException {
        String sql = "SELECT water_type_id FROM water_type WHERE type_name = ?";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1, typeName);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            return rs.getString("water_type_id");
        }
        return null;
    }

    private void deleteUsage() {
        try {
            String sql = "DELETE FROM water_bill WHERE bill_id=?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, idField.getText());
            
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "用水信息删除成功！");
            clearFields();
            refreshTable();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "删除用水信息失败: " + e.getMessage());
        }
    }

    private void clearFields() {
        idField.setText("");
        customerIdField.setSelectedItem(null);
        usageDateField.setText("");
        amountField.setText("");
        waterTypeCombo.setSelectedItem(null);
    }

    private void searchUsage() {
        try {
            StringBuilder sql = new StringBuilder(
                "SELECT u.*, c.name as customer_name FROM usage u " +
                "LEFT JOIN customer c ON u.customer_id = c.customer_id WHERE 1=1");
            
            // 构建查询条件
            if (!idField.getText().trim().isEmpty()) {
                sql.append(" AND u.usage_id LIKE ?");
            }
            if (customerIdField.getSelectedItem() != null) {
                sql.append(" AND (u.customer_id LIKE ? OR c.name LIKE ?)");
            }
            if (!usageDateField.getText().trim().isEmpty()) {
                sql.append(" AND u.usage_date LIKE ?");
            }
            if (!amountField.getText().trim().isEmpty()) {
                sql.append(" AND u.amount = ?");
            }

            PreparedStatement pstmt = connection.prepareStatement(sql.toString());
            int paramIndex = 1;

            // 设置查询参数
            if (!idField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + idField.getText().trim() + "%");
            }
            if (customerIdField.getSelectedItem() != null) {
                String selectedCustomer = customerIdField.getSelectedItem().toString();
                String searchText = "%" + selectedCustomer + "%";
                pstmt.setString(paramIndex++, searchText);
                pstmt.setString(paramIndex++, searchText);
            }
            if (!usageDateField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + usageDateField.getText().trim() + "%");
            }
            if (!amountField.getText().trim().isEmpty()) {
                pstmt.setDouble(paramIndex++, Double.parseDouble(amountField.getText().trim()));
            }

            // 清空表格
            DefaultTableModel model = (DefaultTableModel) usageTable.getModel();
            model.setRowCount(0);

            // 执行查询并显示结果
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String customerName = rs.getString("customer_name");
                String customerId = rs.getString("customer_id");
                String customerDisplay = customerName != null ? 
                    customerName + " (" + customerId + ")" : customerId;
                
                model.addRow(new Object[]{
                    rs.getString("usage_id"),
                    customerDisplay,
                    rs.getString("usage_date"),
                    rs.getDouble("amount")
                });
            }

            if (model.getRowCount() == 0) {
                JOptionPane.showMessageDialog(this, "未找到匹配的记录！");
            }

        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "查询失败: " + e.getMessage());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "用水量必须是数字！");
        }
    }
} 